package com.ctshk.rpc.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.AreaType;
import com.ctshk.common.enums.SystemBusinessType;
import com.ctshk.common.enums.appUser.CertificateTypeEnum;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.rpc.air.dto.AirProductInfoDTO;
import com.ctshk.rpc.air.service.IAirProductService;
import com.ctshk.rpc.bus.dto.BusProductDTO;
import com.ctshk.rpc.bus.service.IBusProductService;
import com.ctshk.rpc.season.dto.FixedSeasonDetailsDTO;
import com.ctshk.rpc.season.dto.FixedSeasonProductCertificatesDTO;
import com.ctshk.rpc.season.service.ISeasonFixedProductPackageService;
import com.ctshk.rpc.season.service.ISeasonFixedProductService;
import com.ctshk.rpc.ship.dto.ShipProductViewDetailDTO;
import com.ctshk.rpc.ship.service.IShipProductService;
import com.ctshk.rpc.system.dto.AreaDTO;
import com.ctshk.rpc.system.dto.MainDataRowFieldDataDTO;
import com.ctshk.rpc.system.service.IMainDataTableService;
import com.ctshk.rpc.system.service.ISysAreaService;
import com.ctshk.rpc.train.dto.TrainProductDTO;
import com.ctshk.rpc.train.service.ITrainProductService;
import com.ctshk.rpc.user.dto.UserMainDataRowFieldDataDTO;
import com.ctshk.rpc.user.service.IUserElasticsearchService;
import com.google.common.collect.Lists;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 * ES接口服务类
 * </p>
 *
 * @author 李新科
 * @date 2021/6/2 11:00
 */
@DubboService
public class UserElasticsearchServiceImpl implements IUserElasticsearchService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @DubboReference
    private IMainDataTableService mainDataTableService;

    @DubboReference
    private ISysAreaService sysAreaService;

    @DubboReference
    private IAirProductService airProductService;

    @DubboReference
    private IShipProductService shipProductService;

    @DubboReference
    private ITrainProductService trainProductService;

    @DubboReference
    private ISeasonFixedProductService seasonFixedProductService;

    @DubboReference
    private IBusProductService busProductService;

    @DubboReference
    private ISeasonFixedProductPackageService seasonFixedProductPackageService;

    @Override
    public Result<List<CertificateTypeEnum>> getCertificatesDataByTypeAndProductId(Long productId, Integer type) {
        List<CertificateTypeEnum> result = new ArrayList<>();
        // 业务类型集合
        List<Integer> typeList = new ArrayList<>();
        // TODO 后期优化:从ES里根据id查询,再根据index名称判断业务类型 查出对应的出发地,目的地属于香港,内地(包括澳门),国际,取证件数据交集,
        //  现在先根据业务类型type去对应的单项服务查询
        Long depCityId = null;
        Long arrCityId = null;
        // 出发地地区类型
        Integer depAreaType = null;
        // 目的地地区类型
        Integer arrAreaType = null;
        if(SystemBusinessType.AIR_TICKET.getCode() == type) {
            AirProductInfoDTO productDTO = airProductService.getById(productId);
            depCityId = productDTO.getDepCityId();
            arrCityId = productDTO.getArrCityId();
            typeList.add(type);
        } else if(SystemBusinessType.HOTEL.getCode() == type) {
            typeList.add(type);
        } else if(SystemBusinessType.SHIP_TICKET.getCode() == type) {
            ShipProductViewDetailDTO shipProductViewDetailDTO = shipProductService.queryProductDetail(productId);
            depCityId = shipProductViewDetailDTO.getDepCityId();
            arrCityId = shipProductViewDetailDTO.getArrCityId();
            typeList.add(type);
        } else if(SystemBusinessType.TRAIN_TICKET.getCode() == type) {
            TrainProductDTO trainProductDTO = trainProductService.queryDetail(productId);
            depCityId = trainProductDTO.getDepartureCityId();
            arrCityId = trainProductDTO.getArriveCityId();
            typeList.add(type);
        } else if(SystemBusinessType.BUS_TICKET.getCode() == type) {
            BusProductDTO busProductDTO = busProductService.queryDetail(productId);
            depCityId = busProductDTO.getDepartureCityId();
            arrCityId = busProductDTO.getArriveCityId();
            typeList.add(type);
        } else if(SystemBusinessType.FIXED_PACKAGE_TICKET.getCode() == type) {
            FixedSeasonProductCertificatesDTO dto = seasonFixedProductService.getPackageProductByProductId(productId);
            depCityId = dto.getDepCityId();
            arrCityId = dto.getArrCityId();
            String packageProductFlag = dto.getPackageProductFlag();
            String str[] = packageProductFlag.split(",");
            typeList = Stream.of(str).map(s -> {
                return Integer.valueOf(s);
            }).collect(Collectors.toList());
        }



        List<AreaDTO> areaDTOS = sysAreaService.queryAreaDTOListByEsIds(Lists.newArrayList(depCityId, arrCityId));
        for (AreaDTO areaDTO : areaDTOS) {
            Long id = areaDTO.getId();
            String countryCode = areaDTO.getCountryCode();
            if(depCityId.longValue() == id.longValue()) {
                if("4RS".equals(countryCode) || "7ID".equals(countryCode) || "CP4".equals(countryCode)) {
                    depAreaType = AreaType.DOMESTIC.getCode();
                } else if("824".equals(countryCode)) {
                    depAreaType = AreaType.HK.getCode();
                } else {
                    depAreaType = AreaType.FOREIGN.getCode();
                }
            } else if (arrCityId.longValue() == id.longValue()) {
                if("4RS".equals(countryCode) || "7ID".equals(countryCode) || "CP4".equals(countryCode)) {
                    arrAreaType = AreaType.DOMESTIC.getCode();
                } else if("824".equals(countryCode)) {
                    arrAreaType = AreaType.HK.getCode();
                } else {
                    arrAreaType = AreaType.FOREIGN.getCode();
                }
            }
        }

        result = getDataByTypeListAndDepAndArr(typeList,depAreaType,arrAreaType);


        /*SearchSourceBuilder searchSource = new SearchSourceBuilder();
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        boolQuery.must(QueryBuilders.matchQuery("id", productId));

        searchSource.query(boolQuery);
        searchSource.size(1);
        SearchRequest searchRequest = new SearchRequest().source(searchSource);
        try {
            SearchResponse response = restHighLevelClient.search(searchRequest, ElasticSearchConfiguration.COMMON_OPTIONS);
            SearchHit[] hits = response.getHits().getHits();
            for (SearchHit hit : hits) {
                // 获取索引
                String index = hit.getIndex();

                String obj = hit.getSourceAsString();
                System.out.println(obj);
                List<MainDataRowFieldDataDTO> mainDataRowFieldDataDTOS = mainDataTableService.groupByDataField(1348475429155237889L, 1348477526361763842L);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }*/
        return Result.success(result);
    }

    private List<CertificateTypeEnum> getDataByTypeListAndDepAndArr(List<Integer> typeList,Integer depAreaType,Integer arrAreaType) {
        List<CertificateTypeEnum> result = new ArrayList<>();
        if(AreaType.HK.getCode().equals(depAreaType) && AreaType.DOMESTIC.getCode().equals(arrAreaType)) {
            // 香港 - 内地
            for (Integer type : typeList) {
                List<CertificateTypeEnum> list = new ArrayList<>();
                if(SystemBusinessType.AIR_TICKET.getCode() == type) {
                    // 回乡证,护照,港澳通行证
                    list.add(CertificateTypeEnum.CERTIFICATE_TYPE_2);
                    list.add(CertificateTypeEnum.CERTIFICATE_TYPE_3);
                    list.add(CertificateTypeEnum.CERTIFICATE_TYPE_4);
                } else if(SystemBusinessType.SHIP_TICKET.getCode() == type) {
                    // 回乡证,护照,台胞证,国内身份证,香港身份证,港澳通行证
                    list.add(CertificateTypeEnum.CERTIFICATE_TYPE_1);
                    list.add(CertificateTypeEnum.CERTIFICATE_TYPE_2);
                    list.add(CertificateTypeEnum.CERTIFICATE_TYPE_3);
                    list.add(CertificateTypeEnum.CERTIFICATE_TYPE_4);
                    list.add(CertificateTypeEnum.CERTIFICATE_TYPE_5);
                    list.add(CertificateTypeEnum.CERTIFICATE_TYPE_6);
                } else if(SystemBusinessType.TRAIN_TICKET.getCode() == type) {
                    // 回乡证,护照,台胞证,国内身份证
                    list.add(CertificateTypeEnum.CERTIFICATE_TYPE_2);
                    list.add(CertificateTypeEnum.CERTIFICATE_TYPE_4);
                    list.add(CertificateTypeEnum.CERTIFICATE_TYPE_5);
                    list.add(CertificateTypeEnum.CERTIFICATE_TYPE_6);
                }
                if(CollectionUtils.isEmpty(list)) {
                    continue;
                }
                if(CollectionUtils.isEmpty(result)) {
                    result = list;
                } else {
                    result = result.stream().filter(item -> list.contains(item)).collect(Collectors.toList());
                }
            }

        } else if(AreaType.HK.getCode().equals(depAreaType) && AreaType.FOREIGN.getCode().equals(arrAreaType)) {
            // 香港 - 国际
            for (Integer type : typeList) {
                List<CertificateTypeEnum> list = new ArrayList<>();
                if(SystemBusinessType.AIR_TICKET.getCode() == type) {
                    // 护照
                    list.add(CertificateTypeEnum.CERTIFICATE_TYPE_4);
                }
                if(CollectionUtils.isEmpty(list)) {
                    continue;
                }
                if(CollectionUtils.isEmpty(result)) {
                    result = list;
                } else {
                    result = result.stream().filter(item -> list.contains(item)).collect(Collectors.toList());
                }
            }
            result = getDataByTypeList(typeList);
        } else if(AreaType.DOMESTIC.getCode().equals(depAreaType) && AreaType.HK.getCode().equals(arrAreaType)) {
            // 内地 - 香港
            for (Integer type : typeList) {
                List<CertificateTypeEnum> list = new ArrayList<>();
                if(SystemBusinessType.AIR_TICKET.getCode() == type) {
                    // 回乡证,护照,港澳通行证
                    list.add(CertificateTypeEnum.CERTIFICATE_TYPE_2);
                    list.add(CertificateTypeEnum.CERTIFICATE_TYPE_3);
                    list.add(CertificateTypeEnum.CERTIFICATE_TYPE_4);
                } else if(SystemBusinessType.SHIP_TICKET.getCode() == type) {
                    // 回乡证,护照,台胞证,国内身份证,香港身份证,港澳通行证
                    list.add(CertificateTypeEnum.CERTIFICATE_TYPE_1);
                    list.add(CertificateTypeEnum.CERTIFICATE_TYPE_2);
                    list.add(CertificateTypeEnum.CERTIFICATE_TYPE_3);
                    list.add(CertificateTypeEnum.CERTIFICATE_TYPE_4);
                    list.add(CertificateTypeEnum.CERTIFICATE_TYPE_5);
                    list.add(CertificateTypeEnum.CERTIFICATE_TYPE_6);
                } else if(SystemBusinessType.TRAIN_TICKET.getCode() == type) {
                    // 回乡证,护照,台胞证,国内身份证
                    list.add(CertificateTypeEnum.CERTIFICATE_TYPE_2);
                    list.add(CertificateTypeEnum.CERTIFICATE_TYPE_4);
                    list.add(CertificateTypeEnum.CERTIFICATE_TYPE_5);
                    list.add(CertificateTypeEnum.CERTIFICATE_TYPE_6);
                }
                if(CollectionUtils.isEmpty(list)) {
                    continue;
                }
                if(CollectionUtils.isEmpty(result)) {
                    result = list;
                } else {
                    result = result.stream().filter(item -> list.contains(item)).collect(Collectors.toList());
                }
            }
        } else if(AreaType.DOMESTIC.getCode().equals(depAreaType) && AreaType.DOMESTIC.getCode().equals(arrAreaType)) {
            // 内地 - 内地
            for (Integer type : typeList) {
                List<CertificateTypeEnum> list = new ArrayList<>();
                if(SystemBusinessType.AIR_TICKET.getCode() == type) {
                    // 回乡证,护照,身份证
                    list.add(CertificateTypeEnum.CERTIFICATE_TYPE_2);
                    list.add(CertificateTypeEnum.CERTIFICATE_TYPE_4);
                    list.add(CertificateTypeEnum.CERTIFICATE_TYPE_5);
                } else if(SystemBusinessType.SHIP_TICKET.getCode() == type) {
                    // 回乡证,护照,台胞证,国内身份证,香港身份证,港澳通行证
                    list.add(CertificateTypeEnum.CERTIFICATE_TYPE_1);
                    list.add(CertificateTypeEnum.CERTIFICATE_TYPE_2);
                    list.add(CertificateTypeEnum.CERTIFICATE_TYPE_3);
                    list.add(CertificateTypeEnum.CERTIFICATE_TYPE_4);
                    list.add(CertificateTypeEnum.CERTIFICATE_TYPE_5);
                    list.add(CertificateTypeEnum.CERTIFICATE_TYPE_6);
                }
                if(CollectionUtils.isEmpty(list)) {
                    continue;
                }
                if(CollectionUtils.isEmpty(result)) {
                    result = list;
                } else {
                    result = result.stream().filter(item -> list.contains(item)).collect(Collectors.toList());
                }
            }
        } else if(AreaType.DOMESTIC.getCode().equals(depAreaType) && AreaType.FOREIGN.getCode().equals(arrAreaType)) {
            // 内地 - 国际
            for (Integer type : typeList) {
                if(SystemBusinessType.AIR_TICKET.getCode() == type) {
                    // 护照
                    result.add(CertificateTypeEnum.CERTIFICATE_TYPE_4);
                }
            }

        }

        return result;
    }

    private List<CertificateTypeEnum> getDataByTypeList(List<Integer> typeList) {
        List<CertificateTypeEnum> result = new ArrayList<>();
        return result;
    }

}
